package com.paschino.controller;

import java.awt.Image;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.paschino.bean.NewsBean;
import com.paschino.modal.Album;
import com.paschino.modal.Category;
import com.paschino.modal.News;
import com.paschino.modal.Product;
import com.paschino.modal.StoreImage;
import com.paschino.service.AlbumService;
import com.paschino.service.CategoryService;
import com.paschino.service.ImageService;
import com.paschino.service.NewsService;
import com.paschino.service.ProductService;
import com.paschino.service.RoleService;
import com.paschino.service.UserService;
import com.paschino.utils.ControllerService;

@Controller
public class HomeController {

	@Autowired
	private RoleService roleService;

	@Autowired
	private UserService userService;

	@Autowired
	ImageService imageService;

	@Autowired
	AlbumService albumService;

	@Autowired
	NewsService newsService;

	@Autowired
	ServletContext servletContext;

	@Autowired
	CategoryService cateService;

	@Autowired
	ProductService productService;

	@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
	public ModelAndView showHomePage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		Album album = albumService.getAlbumByName("Slider");
		imageList = prepareListSliderBean(album);
		List<NewsBean> listTopNews = prepareListNewsBean(newsService
				.getTopNewsHomePage());
		writeImage(imageList, album.getName());
		writeImageNews(listTopNews);
		model.put("slider", imageList);
		model.put("listTopNews", listTopNews);
		request.setAttribute("sessionHome", "home");
		ModelAndView mv = new ModelAndView("home", model);
		return mv;
	}

	@RequestMapping(value = "/about", method = RequestMethod.GET)
	public ModelAndView showAboutPage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		Album album = albumService.getAlbumByName("Slider");
		imageList = prepareListSliderBean(album);
		model.put("slider", imageList);
		request.setAttribute("sessionHome", "about");
		ModelAndView mv = new ModelAndView("about", model);
		return mv;
	}

	@RequestMapping(value = "/menu", method = RequestMethod.GET)
	public ModelAndView showMenuPage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		List<Category> cateList = cateService.getCategoryListByActive();
		List<Product> listAllProducts = new ArrayList<Product>();
		List<Product> listProductByCate = new ArrayList<Product>();
		Album album = albumService.getAlbumByName("Slider");
		imageList = prepareListSliderBean(album);
		for (Category cate : cateList) {
			listProductByCate = productService
					.getProductListByCateAndIsActive(cate);
			for (Product product : listProductByCate) {
				listAllProducts.add(product);
			}
		}
		model.put("cateList", cateList);
		model.put("listAllProducts", listAllProducts);
		model.put("slider", imageList);
		request.setAttribute("sessionHome", "menu");
		ModelAndView mv = new ModelAndView("menu", model);
		return mv;
	}

	@RequestMapping(value = "/news", method = RequestMethod.GET)
	public ModelAndView showNewsPage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		List<NewsBean> listNews = prepareListNewsBean(newsService
				.getNewsListHomePage());
		Album album = albumService.getAlbumByName("Slider");
		imageList = prepareListSliderBean(album);
		writeImageNews(listNews);
		model.put("slider", imageList);
		model.put("listNews", listNews);
		request.setAttribute("sessionHome", "news");
		ModelAndView mv = new ModelAndView("news", model);
		return mv;
	}

	@RequestMapping(value = "/career", method = RequestMethod.GET)
	public ModelAndView showCareerPage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		List<StoreImage> imageListCareer = new ArrayList<StoreImage>();
		Album album = albumService.getAlbumByName("Slider");
		Album albumCareer = albumService.getAlbumByName("Career");
		imageList = prepareListSliderBean(album);
		imageListCareer = prepareListSliderBean(albumCareer);
		model.put("slider", imageList);
		model.put("career", imageListCareer);
		request.setAttribute("sessionHome", "career");
		ModelAndView mv = new ModelAndView("career", model);
		return mv;
	}

	@RequestMapping(value = "/contact", method = RequestMethod.GET)
	public ModelAndView showContactPage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		Album album = albumService.getAlbumByName("Slider");
		imageList = prepareListSliderBean(album);
		model.put("slider", imageList);
		request.setAttribute("sessionHome", "contact");
		ModelAndView mv = new ModelAndView("contact", model);
		return mv;
	}

	@RequestMapping(value = "/library", method = RequestMethod.GET)
	public ModelAndView showLibraryPage(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		List<StoreImage> libraryAlbumImage = new ArrayList<StoreImage>();
		List<StoreImage> libraryImageList = new ArrayList<StoreImage>();
		Album album = albumService.getAlbumByName("Slider");
		List<Album> albumList = albumService.getLibraryAlbum();
		for (Album libraryAlbum : albumList) {
			libraryAlbumImage = prepareListSliderBean(libraryAlbum);
			writeImage(libraryAlbumImage, libraryAlbum.getName());
			for (StoreImage storeImage : libraryAlbumImage) {
				libraryImageList.add(storeImage);
			}
		}

		imageList = prepareListSliderBean(album);
		model.put("slider", imageList);
		model.put("albumList", albumList);
		model.put("libraryImageList", libraryImageList);
		request.setAttribute("sessionHome", "library");
		ModelAndView mv = new ModelAndView("library", model);
		return mv;
	}

	@RequestMapping(value = "/detailnews", method = RequestMethod.GET)
	public ModelAndView showDetailNewsPage(HttpServletRequest request,
			HttpServletResponse response) {
		String newsID = request.getParameter("newsID");
		NewsBean newsBean = new NewsBean();
		newsBean = prepareNewsBean(newsID);
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		Album album = albumService.getAlbumByName("Slider");
		imageList = prepareListSliderBean(album);
		model.put("slider", imageList);
		model.put("newsDetail", newsBean);
		request.setAttribute("sessionHome", "news");
		ModelAndView mv = new ModelAndView("detailnews", model);
		return mv;
	}

	private List<StoreImage> prepareListSliderBean(Album album) {
		// List<AlbumBean> list = new ArrayList<AlbumBean>();
		List<StoreImage> images = new ArrayList<StoreImage>();
		images = imageService.getListImageByIsShow(album);

		return images;
	}

	private void writeImageNews(List<NewsBean> listNews) {
		String folder = "news-images";
		String location = servletContext.getRealPath("/");
		String foldername = location + File.separator + "resources"
				+ File.separator + folder;
		String fileName = "";
		File file = null;
		File folderFile = null;
		StoreImage storeImage = new StoreImage();
		for (NewsBean nBean : listNews) {
			try {
				fileName = nBean.getImage();
				file = new File(foldername + File.separator + fileName);
				folderFile = new File(foldername);
				if (!file.exists()) {
					if (!folderFile.exists()) {
						folderFile.mkdir();
					}
					storeImage = imageService.getImageByGroupBy(fileName,
							"NEWS");
					byte[] bFile = storeImage.getData();
					FileUtils.writeByteArrayToFile(file, bFile);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void writeImage(List<StoreImage> imageList, String name) {
		String folder = name.toLowerCase() + "-images";
		String location = servletContext.getRealPath("/");
		String foldername = location + File.separator + "resources"
				+ File.separator + folder;
		String fileName = "";
		File file = null;
		File folderFile = null;
		StoreImage storeImage = new StoreImage();
		for (StoreImage sImage : imageList) {
			try {
				fileName = sImage.getName();
				file = new File(foldername + File.separator + fileName);
				folderFile = new File(foldername);
				if (!file.exists()) {
					if (!folderFile.exists()) {
						folderFile.mkdir();
					}
					storeImage = imageService.getImageByGroupBy(fileName,
							name.toUpperCase());
					byte[] bFile = storeImage.getData();
					FileUtils.writeByteArrayToFile(file, bFile);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private List<NewsBean> prepareListNewsBean(List<News> newsList) {
		List<NewsBean> list = new ArrayList<NewsBean>();
		for (News n : newsList) {
			NewsBean b = new NewsBean();
			b.setId(n.getId());
			b.setName(n.getName());
			b.setShortdescen(n.getShortdescen());
			b.setShortdescvi(n.getShortdescvi());
			try {
				b.setFulldescvi(new String(n.getFulldescvi(), "UTF-8"));
				b.setFulldescen(new String(n.getFulldescen(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			b.setProcessDate(n.getProcessDate());
			b.setUser(n.getUser());
			b.setIsActive(n.getIsActive());
			b.setImage(n.getImage());
			list.add(b);
		}
		return list;
	}

	private NewsBean prepareNewsBean(String newsId) {
		NewsBean newsBean = new NewsBean();
		News news = newsService.getNews(Integer.parseInt(newsId));
		if (null != news) {
			newsBean.setId(news.getId());
			newsBean.setName(news.getName());
			try {
				newsBean.setFulldescen(new String(news.getFulldescen(), "UTF-8"));
				newsBean.setFulldescvi(new String(news.getFulldescvi(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			newsBean.setShortdescen(news.getShortdescen());
			newsBean.setShortdescvi(news.getShortdescvi());
			newsBean.setImage(news.getImage());
			newsBean.setProcessDate(news.getProcessDate());
			newsBean.setUser(news.getUser());
			newsBean.setIsActive(news.getIsActive());
		}
		return newsBean;
	}
}
